package sjz.ax.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sjz.ax.config.AccessToken;
import sjz.ax.config.WxConfig;
import sjz.ax.util.UrlUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

import static sjz.ax.util.UrlUtils.*;

@Controller
public class LoginController {

    @Resource
    private WxConfig wxConfig;

    @RequestMapping("/login")
    public void login(HttpServletResponse response){
        StringBuilder sb = new StringBuilder("https://open.weixin.qq.com/connect/qrconnect?");
        sb.append("appid=");
        sb.append(wxConfig.getAppId());
        sb.append("&redirect_uri=");
        sb.append(wxConfig.getRedirectUri());
        sb.append("&response_type=code");
        sb.append("&scope=snsapi_login&state=STATE#wechat_redirect");
        try {
            response.sendRedirect(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/wxloginCallback")
    public void wxloginCallback(@RequestParam String code,
                               HttpServletResponse response,
                               HttpServletRequest request){
        StringBuilder sb = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?");
        sb.append("appid=");
        sb.append(wxConfig.getAppId());
        sb.append("&secret=");
        sb.append(wxConfig.getAppSecret());
        sb.append("&code=" + code);
        sb.append("&grant_type=authorization_code");
        // 获取 token
        String accesstoken = loadURL(sb.toString());
        System.out.println(accesstoken);
        AccessToken token = JSON.parseObject(accesstoken, AccessToken.class);
        //请求并获取用户信息
        StringBuilder sbUserInfo = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?");
        sbUserInfo.append("access_token=" + token.getAccess_token());
        sbUserInfo.append("&openid=" + token.getOpenid());
        //
        String userinfo = loadURL(sbUserInfo.toString());
        try {
            response.getWriter().println("userinfo=" + userinfo);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
